'use strict';

const Controller = require('egg').Controller;

class FavoriteController extends Controller {
  // 获取收藏列表（包含岗位信息）
  async index() {
    const { ctx } = this;
<<<<<<< HEAD
    const userId = ctx.query.userId || 1; // 临时使用默认用户ID
=======
    // 从JWT token中获取用户ID
    const userId = ctx.user?.id;
    if (!userId) {
      ctx.status = 401;
      ctx.body = {
        success: false,
        message: '未登录'
      };
      return;
    }
>>>>>>> resume
    const favorites = await ctx.service.favorite.listWithJobInfo(userId);
    ctx.body = {
      success: true,
      data: favorites
    };
  }

<<<<<<< HEAD
  // 添加收藏
  async create() {
    const { ctx } = this;
    const { jobId, jobInfo } = ctx.request.body;
    const userId = ctx.request.body.userId || 1; // 临时使用默认用户ID
    
    const result = await ctx.service.favorite.add(userId, jobId, jobInfo);
    ctx.body = result;
  }

=======
  async create() {
    const { ctx } = this;
    try {
      const { jobId, jobInfo } = ctx.request.body;
      // 从JWT token中获取用户ID
      const userId = ctx.user?.id;
      if (!userId) {
        ctx.status = 401;
        ctx.body = { success: false, message: '未登录' };
        return;
      }
      
      // 参数验证
      if (!jobId) {
        ctx.status = 400;
        ctx.body = { success: false, message: '参数jobId不能为空' };
        return;
      }

      const result = await ctx.service.favorite.add(userId, jobId, jobInfo);
      ctx.body = result;
    } catch (error) {
      ctx.logger.error('收藏控制器错误:', error);
      ctx.status = 500;
      ctx.body = { success: false, message: '服务器内部错误' };
    }
  }
>>>>>>> resume
  // 取消收藏
  async destroy() {
    const { ctx } = this;
    const { jobId } = ctx.params;
<<<<<<< HEAD
    const userId = ctx.query.userId || 1; // 临时使用默认用户ID
=======
    // 从JWT token中获取用户ID
    const userId = ctx.user?.id;
    if (!userId) {
      ctx.status = 401;
      ctx.body = { success: false, message: '未登录' };
      return;
    }
>>>>>>> resume
    
    const result = await ctx.service.favorite.remove(userId, jobId);
    ctx.body = result;
  }

  // 检查是否已收藏
  async check() {
    const { ctx } = this;
    const { jobId } = ctx.query;
<<<<<<< HEAD
    const userId = ctx.query.userId || 1; // 临时使用默认用户ID
=======
    // 从JWT token中获取用户ID
    const userId = ctx.user?.id;
    if (!userId) {
      ctx.status = 401;
      ctx.body = { success: false, message: '未登录' };
      return;
    }
>>>>>>> resume
    
    const isFavorite = await ctx.service.favorite.isFavorite(userId, jobId);
    ctx.body = {
      success: true,
      data: { isFavorite }
    };
  }
}

module.exports = FavoriteController;